<%@ page import="com.google.common.collect.Maps" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.engine.jucailinkq.common.util.DateUtil" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="com.engine.jucailinkq.common.util.DbTools" %>
<%@ page import="com.engine.jucailinkq.common.util.CommonUtil" %>
<%@ page import="org.apache.commons.lang3.StringUtils" %>
<%@ page import="java.util.Set" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="com.engine.jucailinkq.attendance.attendanceplan.service.AttendancePlanService" %>
<%@ page import="com.engine.jucailinkq.attendance.attendanceanalysis.wrapper.AttendanceAnalysisWrapper" %>
<%@ page import="com.engine.jucailinkq.attendance.attendanceplan.service.impl.AttendancePlanServiceImpl" %>
<%@ page import="com.engine.jucailinkq.attendance.attendanceanalysis.service.impl.UtilServiceImpl" %>
<%@ page import="com.engine.common.util.ServiceUtil" %>
<%@ page import="com.engine.jucailinkq.attendance.attendanceanalysis.service.UtilService" %>
<%@ page import="com.engine.jucailinkq.attendance.workflow.service.AllowanceService" %>
<%@ page import="com.engine.jucailinkq.attendance.workflow.service.impl.AllowanceServiceImpl" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.stream.Collectors" %>
<%@ page import="java.util.Comparator" %>
<%@ page import="java.time.ZoneOffset" %>
<%@ page import="weaver.general.Util" %>
<%
    try {
        String userIds = request.getParameter("userIds");
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");

        out.print("attendence analysis start.");
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            out.print("attendence analysis userIds is null.");
            return;
        }
        Map<String,Object> paramMap = Maps.newHashMap();
        String startBeforeDate = DateUtil.beforeDay(startDate,2);
        String endAfterDate = DateUtil.AfterDay(endDate,2);
        int betweenDays = DateUtil.getBetWeenDays(startDate,endDate);

        RecordSet rs = new RecordSet();
        String queryDepartEmployeeSql = "select resourceid id,changedate name from HRMSTATUSHISTORY  where type_n = 5";
        // 获取离职日期
        Map<String,Object> departEmployeeMap = DbTools.getSqlToMapList(queryDepartEmployeeSql);

        AttendancePlanService basicsetService = ServiceUtil.getService(AttendancePlanServiceImpl.class);
        UtilService utilService = ServiceUtil.getService(UtilServiceImpl.class);
        AttendanceAnalysisWrapper attendanceAnalysisService = ServiceUtil.getService(AttendanceAnalysisWrapper.class);
        AllowanceService allowanceService = ServiceUtil.getService(AllowanceServiceImpl.class);

        // 初始化扩展类
        CommonUtil.initExtensionClassHolder();

        if (StringUtils.isEmpty(userIds)) {
            rs.executeQuery("select ygid from uf_jcl_kq_cqjg where rq <= ? and rq >= ?", endDate, startDate);
            Set<String> ids = new HashSet<>();
            while (rs.next()) {
                String ygid = rs.getString("ygid");
                if (StringUtils.isNotEmpty(ygid)) {
                    ids.add(ygid);
                }
            }
            userIds = String.join(",", ids);
        }
        if (StringUtils.isEmpty(userIds)) {
            out.print("attendence analysis userIds is null.");
            return;
        }

        BaseBean baseBean = new BaseBean();
        String sql = "select id,userid,signdate,signtime from hrmschedulesign where isincom=1 and userid in ("+userIds+") and  signdate >= ? and signdate <= ? order by signdate,signtime";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,startBeforeDate,endAfterDate);

        String queryUserSql = "select id,companystartdate from hrmresource where id in ("+userIds+")";
        List<Map<String,Object>> userList = DbTools.getSqlToList(queryUserSql);
        Map<String,List<Map<String,Object>>> userGroupMap = userList.stream().collect(Collectors.groupingBy(e->e.get("id").toString()));

        //补打卡记录
        sql = "select id,bdkry userid,dkrq signdate,dksj signtime from uf_jcl_kq_bdkjl where bdkry in ("+userIds+") and dkrq >= ? and dkrq <= ? and jlzt=1 order by dkrq,dksj";
        List<Map<String,Object>> makeUpList = DbTools.getSqlToList(sql,startBeforeDate,endAfterDate);
        if (makeUpList.size() > 0){
            dataList.addAll(makeUpList);
        }

        dataList = dataList.stream().sorted(Comparator.comparing(e->DateUtil.getTime(e.get("signdate")+" "+e.get("signtime")).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());


        Map<String, List<Map<String,Object>>> collect = dataList.stream().collect(Collectors.groupingBy(e -> Util.null2String(e.get("userid"))));

        sql = "select sjzt,sgsj,ygid,rq from uf_jcl_kq_cqjg where rq>=? and rq<=? and ygid in ("+userIds+")";
        List<Map<String,Object>> attendaceResult = DbTools.getSqlToList(sql,startDate,endDate);
        Map<String,List<Map<String,Object>>> attendaceGroupById = attendaceResult.stream().collect(Collectors.groupingBy(e->e.get("ygid").toString()));

        for (String userId : userIds.split(",")){
            // 获得人员考勤项目
            Map<String,Object> param = Maps.newHashMap();
            //入职日期
            String companystartDate = Util.null2String(userGroupMap.get(userId).get(0).get("companystartdate"));
            //离职日期
            String terminationDate = Util.null2String(departEmployeeMap.get(userId));

            //出勤结果，进出时间
            Map<String,Map<String,Object>> clockInTimeMap = Maps.newHashMap();
            param.put("startDate",startBeforeDate);
            param.put("endDate",endAfterDate);
            param.put("resourceId",userId);
            Map<String,Object> dataMap = basicsetService.getAttendanceItemsByPerson(param);
            List<Map<String,Object>> attendanceItems = (List<Map<String,Object>>)dataMap.get("data");

            // 获得人员综合工时
            Map<String,Object> workHourdataMap = basicsetService.getWorkHoursItemByPerson(param);
            List<Map<String,Object>> workHourItems = (List<Map<String,Object>>)workHourdataMap.get("data");

            // 获取人员班次
            Map<String,Object> classesParamMap = Maps.newHashMap();
            classesParamMap.put("tableName","uf_pbjg");
            classesParamMap.put("startDate",startBeforeDate);
            classesParamMap.put("endDate",endAfterDate);
            classesParamMap.put("pblx","0");
            classesParamMap.put("pbdx",userId);
            classesParamMap.put("current","1");
            classesParamMap.put("pageSize",9999);
            classesParamMap.put("recurrence",1);
            classesParamMap.put("clockInTimeMap",clockInTimeMap);
            classesParamMap.put("clockInData",collect.get(userId));
            classesParamMap.put("attendanceItems",attendanceItems);
            Map<String,Object> schedulMap = utilService.getSchedulingInFormation(classesParamMap);

            Map<String, List<Map<String, Object>>> attendaceResultMap = Maps.newHashMap();
            if (attendaceGroupById.get(userId) != null && attendaceGroupById.get(userId).size() > 0) {
                attendaceResultMap = attendaceGroupById.get(userId).stream().collect(Collectors.groupingBy(e -> e.get("rq").toString()));
            }
            for (int i=0; i<=betweenDays;i++){
                String date = DateUtil.AfterDay(startDate,i);
                if (("".equals(companystartDate) || DateUtil.getTime(date).compareTo(DateUtil.getTime(companystartDate)) > 0)
                        && ("".equals(terminationDate) || DateUtil.getTime(date).compareTo(DateUtil.getTime(terminationDate)) < 0)) {
                    try {
                        attendanceAnalysisService.attendanceAnalysisForApi(userId, date, collect.get(userId), attendanceItems, schedulMap, workHourItems, clockInTimeMap, attendaceResultMap.get(date));
                    } catch (Exception e) {
                        baseBean.writeLog("attendance analysisForApi B param:" + userId + "、" + date + "; error:" + e.getMessage());
                    }
                }

                // 入职日期及之前、离职日期及之后的数据逻辑删除
                if ((StringUtils.isNotEmpty(companystartDate) && DateUtil.getTime(date).compareTo(DateUtil.getTime(companystartDate)) <= 0)
                        || (StringUtils.isNotEmpty(terminationDate) && DateUtil.getTime(date).compareTo(DateUtil.getTime(terminationDate)) >= 0)) {
                }
            }
        }
        paramMap.put("empIds",paramMap.get("userIds"));
        allowanceService.addAllowanceRecords(paramMap);
        out.print("attendence analysis end.");
    } catch (Exception e) {
        out.print("attendence analysis error:" + e.getMessage());
    }
%>